import Vue from 'vue'
import store from '../store'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
// import Layout from '@/views/layout/Layout'

/* Router Modules */
import { validateNull } from '@/utils/validate'

import resultCode from '@/utils/resultCode'
import { getResourceMenuList } from '@/api/resource'

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)
const Layout = _import('layout/Layout') // 主模板
const NestLayout = _import('layout/nested') // 多层菜单下的引用空模板
/** note: Submenu only appear when children.length>=1
 *  detail see  https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 **/

/**
* hidden: true                   if `hidden:true` will not show in the sidebar(default is false)
* alwaysShow: true               if set true, will always show the root menu, whatever its child routes length
*                                if not set alwaysShow, only more than one route under the children
*                                it will becomes nested mode, otherwise not show the root menu
*                                为true，在唯一一个子菜单场景下，也会显示父菜单，未false会隐藏父菜单
* redirect: noredirect           if `redirect:noredirect` will no redirect in the breadcrumb
* name:'router-name'             the name is used by <keep-alive> (must set!!!)
* meta : {
    roles: ['admin','editor']     will control the page roles (you can set multiple roles)
    title: 'title'               the name show in submenu and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar,
    noCache: true                if true ,the page will no be cached(default is false)
  }
**/
export const constantRouterMap = [
  // {
  //   path: '/redirect',
  //   component: Layout,
  //   hidden: true,
  //   children: [
  //     {
  //       path: '/redirect/:path*',
  //       component: () => import('@/views/redirect/index')
  //     }
  //   ]
  // },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index'),
    hidden: true,
    meta: { title: '登录', noCache: true }
  },
  {
    path: '/auth-redirect',
    component: () => import('@/views/login/authredirect'),
    hidden: true,
    meta: { title: 'AuthRedirect', noCache: true }
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/errorPage/404'),
    hidden: true,
    meta: { title: '404', noCache: true }
  },
  {
    path: '/401',
    name: '401',
    component: () => import('@/views/errorPage/401'),
    hidden: true,
    meta: { title: '401', noCache: true }
  }
  // {
  //   path: '',
  //   component: Layout,
  //   redirect: 'dashboard',
  //   children: [
  //     {
  //       path: 'dashboard',
  //       component: () => import('@/views/dashboard/index'),
  //       name: 'Dashboard',
  //       meta: { title: 'dashboard', icon: 'dashboard', noCache: true }
  //     }
  //   ]
  // }
]

export default new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
})

export let asyncRouterMap = []

console.log('=========router index begin========')
console.log('store.getters.menus.length = ' + store.getters.menus.length)
if (store.getters.menus.length === 0) { // store.getters.menus.length === 0
  console.log('=========menus init begin========')
  getResourceMenuList().then(response => {
    const result = response.data// 请求接口返回的内容
    if (result.code === resultCode.SUCCESS) {
      handleMenu(result.data)
    }
  })
  console.log('=========menus init end========')
} else {
  console.log('=========menus read form store========')
  console.log(store.getters.menus)
  handleMenu(store.getters.menus)
}
asyncRouterMap.push({ path: '*', redirect: '/404', hidden: true })
console.log('=========router index end========')

// 初始化菜单
function handleMenu(routes) {
  if (!validateNull(routes)) {
    console.log('========routes==========')
    console.log(routes)
    routes.forEach((route, index) => {
      console.log('route=')
      console.log(route)

      if (!validateNull(route.children)) { // 有子菜单
        route.component = Layout
        route.redirect = route.children[0].path
        handleChildMenu(route.children)
      } else { // 没有子菜单
        route.component = _import(route.vue) || null
        const parentRoute = {
          path: route.path,
          hidden: route.hidden,
          permission: route.permission,
          component: Layout,
          meta: route.meta,
          children: [route]
        }

        console.log('=========parentRoute==========')
        console.log(parentRoute)

        routes[index] = parentRoute
        console.log('=========route==========')
        console.log(routes[index])
      }
    })
    asyncRouterMap = routes

    store.dispatch('InitMenu', asyncRouterMap).then(() => {
      console.log('========InitMenu store success==========')
    })

    console.log('========asyncRouterMap==========')
    console.log(asyncRouterMap)
  }
}

// 初始化子菜单
function handleChildMenu(routes) {
  routes.forEach(route => {
    if (!validateNull(route.children)) { // 有子菜单
      console.log('-----route111 name---' + route.name)
      route.component = NestLayout
      route.redirect = route.children[0].path
      route.children.forEach(childRoute => {
        if (!validateNull(childRoute.children)) { // 有子菜单
          handleChildMenu(childRoute.children)
        } else {
          console.log('-----childRoute name---' + childRoute.name)
          childRoute.component = _import(childRoute.vue) || null
        }
      })
    } else { // 没有子菜单
      console.log('-----route name---' + route.name)
      route.component = _import(route.vue) || null
    }
  })
}
